<?php


namespace app\api\controller;

use app\api\model\Discount as discountModel;
use app\api\model\Member;
use app\api\model\Userdiscount;

//http://cosmo.com/api/Discount/receiveDiscount
class Discount extends BaseApi {

    public function getDiscountList(){
        $discount = new discountModel();
        $discountList = $discount->getList();
        if(!$discountList->isEmpty()){
            return json(['code'=>1,'data'=>$discountList]);
        }
        return json(['code'=>-1,'msg'=>'暂无数据']);
    }

    //领取优惠券
    public function receiveDiscount(){
        if(!$this->request->param('openid') || !$this->request->param('discountid')){
            return json(['code'=>-1,'msg'=>'缺少参数']);
        }

        $discountid = intval($this->request->param('discountid'));
        $openid  = trim($this->request->param('openid'));

        //判断是否领取
        $userDiscount = new Userdiscount();
        $item = $userDiscount->getUserDiscount(['openid'=>$openid,'discount_id'=>$discountid]);
        if(!empty($item)){
            return json(['code'=>-1,'msg'=>'对不起,该优惠券您已领取']);
        }

        $discount = new discountModel();
        $discountItem = $discount->getDetail($discountid,['total','title']);

        if(empty($discountItem)){
            return json(['code'=>-1,'msg'=>'优惠券不存在或已删除']);
        }

        $member = new Member();
        $memberItem = $member->getMember($openid);

        if(empty($memberItem)){
            return json(['code'=>-1,'msg'=>'该用户不存在或已删除']);
        }

        $userDiscount->openid = $openid;
        $userDiscount->discount_id = $discountid;
        $userDiscount->verify = 'CSM'.date('Y',time()).$memberItem->id.$discountid;
        $userDiscount->createtime = time();
        $userDiscount->title = $discountItem->title;
        $userDiscount->save();

        if($userDiscount->id){
            $discountItem->total = $discountItem->total + 1;
            $discountItem->save();
            return json(['code'=>1,'msg'=>'领取成功']);
        }
        return json(['code'=>-1,'msg'=>'领取失败']);

    }




}